package pers.fulsun.es.test._04_search;

import java.io.IOException;
import java.util.Map;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import pers.fulsun.es.test._01_ESClient;

public class _09_ESTest_Doc_Search_HighLight {
  private static RestHighLevelClient client = _01_ESClient.getClient();

  public static void main(String[] args) throws IOException {
    // 创建搜索请求对象
    SearchRequest request = new SearchRequest();
    request.indices("user");

    // 构建查询的请求体
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

    // 构建查询方式
    TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "wangwu1");
    sourceBuilder.query(termsQueryBuilder);

    // 构建高亮字段
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    // 设置标签前缀
    highlightBuilder.preTags("<font color='red'>");
    // 设置标签后缀
    highlightBuilder.postTags("</font>");
    // 设置高亮字段
    highlightBuilder.field("name");
    // 设置高亮构建对象
    sourceBuilder.highlighter(highlightBuilder);

    request.source(sourceBuilder);

    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    // 查询匹配
    SearchHits hits = response.getHits();
    System.out.println("took:" + response.getTook());
    System.out.println("timeout:" + response.isTimedOut());
    System.out.println("total:" + hits.getTotalHits());
    System.out.println("MaxScore:" + hits.getMaxScore());
    System.out.println("hits========>>");
    for (SearchHit hit : hits) {
      // 输出每条查询的结果信息
      System.out.println(hit.getSourceAsString());
      // 打印高亮结果
      Map<String, HighlightField> highlightFields = hit.getHighlightFields();
      System.out.println(highlightFields);
    }
    System.out.println("<<========");
    // 关闭客户端连接
    client.close();
  }
}
